import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';
import { mnetService } from "../../mnet/mnetService";
import { createNatsForwarder, natsForwarderData } from "../../mnet/natsForwarder";

type roomServiceData = {
    nats:natsForwarderData 
}

export class roomService extends mnetService {
 
    async start() {
        this.data.nats = await createNatsForwarder(this.ownerObj)
    }

    get data():roomServiceData {
        return this.getData<roomServiceData>()
    }
}

export function getRoomServiceName(idx:number) {
    return `room_${idx}`
}

if (isMainThread) {
    // 主线程逻辑
    const worker = new Worker(__filename, {
      workerData: { 
        taskId: 'calc_20250227',
        maxNumber: 1e7 
      }
    });
  
    // 接收工作线程消息
    worker.on('message', (result: { primeCount: number; duration: number }) => {
      console.log(`[主线程] 收到计算结果：
      ├ 质数数量: ${result.primeCount.toLocaleString()}
      └ 耗时: ${result.duration.toFixed(2)}ms`);
      worker.unref();
    });
  
    // 错误处理
    worker.on('error', (err) => {
      console.error('[主线程] 工作线程错误:', err);
    });
  
    console.log('[主线程] 已启动计算任务');
  } else {
  
    // 执行计算并返回结果
    const start = performance.now();
    const duration = performance.now() - start;
  
    parentPort?.postMessage({ 
      taskId: workerData.taskId, 
      duration 
    });
  }